package Rservetest.Rservetest;
import static org.math.R.RserveSession.*;

import java.io.File;
import java.util.Properties;

import org.math.R.RserveSession;
import org.math.R.RserverConf;
import org.math.R.Rsession;
import org.math.R.Rsession.RException;

public class Demo {
	public static void main(String args[]) throws RException {
		//Rsession s = RserveSession.newInstanceTry(System.out, null);
		RserverConf rconf = new RserverConf("10.10.10.56", 6311, "", "", new Properties());		
		Rsession s = null;
		//远程R服务器运行Rserve::Rserve(args=' --no-restore --no-save --slave --RS-enable-remote',quote=F)
		s = RserveSession.newRemoteInstance(System.out, rconf);
		s.setCRANRepository("https://mirrors.tuna.tsinghua.edu.cn/CRAN/");
		double[] rand = (double[]) s.eval("rnorm(10)",false); //create java variable from R command
		rand = (double[]) s.eval(String.format("rnorm(%s)","100"),false); //use String.format to parametrize Command Strings 
		s.set("c", Math.random()); //create R variable from java one

		s.save(new File("save.Rdata"), "c"); //save variables in .Rdata
		s.rm("c"); //delete variable in R environment
		s.load(new File("save.Rdata")); //load R variable from .Rdata

		s.set("df", new double[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}, "x1", "x2", "x3"); //create data frame from given vectors
		double value= (Double) ((s.eval("df$x1[3]"))); //access one value in data frame        

		s.toJPEG(new File("plot.jpg"), 400, 400, "plot(rnorm(10))"); //create jpeg file from R graphical command (like plot)

		String html = s.asHTML("summary(rnorm(100))"); //format in html using R2HTML
		System.out.println(html);

		String txt = s.asString("summary(rnorm(100))"); //format in text
		System.out.println(txt);        

		System.out.println(s.installPackage("spgwr",true)); //install and load R package
		System.out.println(s.installPackage("spBayes", true));

		s.close();
	}
}
